<?php

class ConnectionManager {

    private static $instance;
    private $result = null;
    private $databaseConnection = null;
    private $sql = "";

    private function ConnectionManager() {
        $this->databaseConnection = mysql_connect("localhost", "root", "root") or die("cannot connect database");
        mysql_select_db("giaan", $this->databaseConnection);
        mysql_query("SET NAMES 'utf8'");
    }

    public static function getInstance() {
        if (!self::$instance)
            self::$instance = new ConnectionManager();
        return self::$instance;
    }

    public function setQuery($sql) {
        $this->sql = $sql;
    }

    public function fetch($query) {
        return mysql_fetch_array($query);
    }

    public function getNumRows() {
        return mysql_num_rows($this->result);
    }

    public function query() {
        $this->result = mysql_query($this->sql, $this->databaseConnection);
        return $this->result;
    }

    public function closeConnection() {
        if (isset($this->databaseConnection))
            mysql_close($this->databaseConnection);
    }

	// only call after executing insert query statement
	public function getLastId(){
		$this->setQuery("SELECT LAST_INSERT_ID() AS ID");
		$row = $this->fetch($this->query());
		return $row["ID"];
	}

}

?>